package com.cc.jdkjucdemo.CompletableFuture;

import java.util.concurrent.*;

public class CompletableFutureDemo04_01 {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            50,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程start ......");
        long start = System.currentTimeMillis();

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("子线程1开始执行：" + Thread.currentThread().getName());
            System.out.println("子线程1执行中：" + Thread.currentThread().getName());
            int result = 10;
            System.out.println("子线程1执行完成，结果为：" + result);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return result;
        }, executor);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("子线程2开始执行：" + Thread.currentThread().getName());
            System.out.println("子线程2执行中：" + Thread.currentThread().getName());
            int result = 20;
            System.out.println("子线程2执行完成，结果为：" + result);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return result;
        }, executor);
        CompletableFuture<Integer> integerCompletableFuture = future1.thenCombine(future2, Integer::sum);
        System.out.println("主线程等待子线程执行结果：" + integerCompletableFuture.get() + "耗时：" + (System.currentTimeMillis() - start) + "ms");

        System.out.println("主线程end ......");
        executor.shutdown();
    }
}